package com.friend.chat.net

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody


/**
 * @des 处理token过期
 * @date 2021/9/3
 * @author gorilla
 */
class DiamondTokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        try {
            val mediaType = response.body!!.contentType()
            val bodyStr: String = response.body!!.string()
            //上一步会关闭response的流；下面不可以调用response
            val type = object : TypeToken<BaseResult<Any>>() {}.type
            val result: BaseResult<Any> = Gson().fromJson(bodyStr + "", type)
            //非主线程
           /* if (result.status == 99) {
                SPUtils.getInstance().remove(SPUtils.DIAMOND_TOKEN)
                mAppMessage.postValue(MessageBean(MessageBean.DIAMOND_TOKEN_EXPIRED))
            }*/
            return response.newBuilder()
                .body(bodyStr.toResponseBody(mediaType))
                .build();
        } catch (e: Exception) {
            return response
        }
    }
}